#include "StdAfx.h"
#include "JoinLeaveSchedule.h"

CJoinLeaveSchedule::CJoinLeaveSchedule(void)
{
}

CJoinLeaveSchedule::~CJoinLeaveSchedule(void)
{
}

bool CJoinLeaveSchedule::ScheduleStatic(MSEC dwDuration, int nNodeCount , MSEC dwJoinDuration, MSEC dwDepartureDuration)
{
	if(nNodeCount<=0)
	{
		return false;
	}
	if(dwDepartureDuration+dwJoinDuration>dwDuration)
	{
		return false;
	}
	else
	{
		this->m_cBehaverInfo.clear();
		m_cBehaverInfo.assign(nNodeCount,CNodeBehavior());
		for(int i = 0;i<nNodeCount;i++)
		{
			m_cBehaverInfo[i].m_dwJoinTime = rand_range(0,dwJoinDuration);
			m_cBehaverInfo[i].m_dwLeaveTime = rand_range(dwDuration-dwDepartureDuration,dwDuration);
			m_cBehaverInfo[i].m_nNodeIndex = i;
		}
		return true;
	}

}

vector<CNodeBehavior> & CJoinLeaveSchedule::GetScheduleInfo(void)
{
	return this->m_cBehaverInfo;
}

bool CJoinLeaveSchedule::ScheduleDynamic(MSEC dwDuration, double dJoinRate, MSEC dwNodeLifeTime)
{
	if(dwDuration<dwNodeLifeTime)
	{
		return false;
	}
	else
	{
		DWORD dwNodeCount = (DWORD)(dJoinRate*(dwDuration-dwNodeLifeTime)/1000+0.5);
		this->m_cBehaverInfo.clear();
		m_cBehaverInfo.assign(dwNodeCount,CNodeBehavior());
		MSEC nCurTime = 0;
		for(unsigned i = 0;i<dwNodeCount;i++)
		{
			MSEC nInterval = (MSEC)(rand_exp((double)dJoinRate) * 1000.0 + 0.5);
			nCurTime += nInterval;
			MSEC nDuration = (MSEC)(rand_exp(1.0/(double)dwNodeLifeTime)  + 0.5);    // Use exponential life time distribution
			m_cBehaverInfo[i].m_dwJoinTime = nCurTime;
			m_cBehaverInfo[i].m_dwLeaveTime = nCurTime + nDuration;
			m_cBehaverInfo[i].m_nNodeIndex = i;
		}
		return true;
	}
}
